package calendar.commands;

import calendar.model.CalendarModel;
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.services.calendar.CalendarScopes;
import design.patterns.command.Command;

import java.io.InputStreamReader;
import java.util.Collections;

public class Authorize extends Command<Credential> {
    @Override
    protected void protectedExecute() throws Exception {
        // load client secrets
        GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(CalendarModel.JSON_FACTORY,
                new InputStreamReader(CalendarModel.class.getResourceAsStream("/client_secrets.json")));
        if (clientSecrets.getDetails().getClientId().startsWith("Enter")
                || clientSecrets.getDetails().getClientSecret().startsWith("Enter ")) {
            System.out.println(
                    "Enter Client ID and Secret from https://code.google.com/apis/console/?api=calendar "
                            + "into calendar-cmdline-sample/src/main/resources/client_secrets.json");
            System.exit(1);
        }
        // set up authorization code flow
        GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
                CalendarModel.HTTP_TRANSPORT, CalendarModel.JSON_FACTORY, clientSecrets, Collections.singleton(CalendarScopes.CALENDAR))
                .setDataStoreFactory(CalendarModel.DATA_STORE_FACTORY)
                .build();

        // authorize
        setResult(new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user"));
    }
}
